﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SqlFormatter
{
    public partial class DBConnection : Form
    {
        SqlDataAdapter da;
        DataSet ds = new DataSet();

        // Build the Connection String and create a SQL Connection object

        static String cnnStr = "Data Source = localhost; Integrated Security = SSPI; MultipleActiveResultSets=True";

        SqlConnection cnn = new SqlConnection(cnnStr);

        private MainForm mainForm = null;

        public DBConnection()
        {
            InitializeComponent();
           
        }

        public DBConnection(MainForm calledForm)
        {
            mainForm = calledForm as MainForm;
            InitializeComponent();
             
        }

        private void DBConnection_Load(object sender, EventArgs e)
        {

            txtBoxServerName.ReadOnly = true;
            txtBoxUserName.ReadOnly = true;
            txtBoxPwd.ReadOnly = true;

            
        }

        public void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                String cnnStr = string.Empty;
                if (txtBoxServerName.Text != "" || txtBoxUserName.Text != "" || txtBoxPwd.Text != "" || rdbtnSQLLogin.Checked == true)
                {
                    cnnStr = "Data Source =" + txtBoxServerName.Text + "; User ID=" + txtBoxUserName.Text + ";Password=" + txtBoxPwd.Text + ";";
                    cnn.ConnectionString = cnnStr;
                    

                    if (cnn.State.ToString().Equals("Closed"))
                    {
                        cnn.Open();
                    }
                }

                else
                {
                    cnnStr = "Data Source = localhost; Integrated Security = SSPI;";
                    cnn.ConnectionString = cnnStr;
                   

                    if (cnn.State.ToString().Equals("Closed"))
                    {
                        cnn.Open();
                    }
                }

                MainForm.ConnectionString = cnnStr;

                // Create a SQL Command object from the connection object and setup the SELECT command
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT name FROM sys.databases";

                // Create the data adapter to use to get the data and handle connecting to the DB
                da = new SqlDataAdapter(cmd);

                // Get the data from the database. .
                ds.Clear();

                da.Fill(ds, "sys.databases");

                // Connect the cobo box to the data source from where the data is comming from
                // In this case the Customers data table in the dataset.
                //DBcomboBox.DataSource = ds.Tables["sys.databases"];


                DataRow dr = ds.Tables[0].NewRow();
                dr["name"] = "0";
                dr["name"] = "Please select...";
                ds.Tables[0].Rows.InsertAt(dr, 0);

                this.mainForm.DBcomboBox.DataSource = ds.Tables[0];


                this.mainForm.DBcomboBox.DisplayMember = "name";

                // Tell the combo box what collumn to use with the displayed value, value is not displayed
                this.mainForm.DBcomboBox.ValueMember = "name";


                // Tell the combo box what collumn to display to the user
                //DBcomboBox.DisplayMember = "name";

                // Tell the combo box what collumn to use with the displayed value, value is not displayed
                //DBcomboBox.ValueMember = "name";

                // make it readonly
             
                this.mainForm.DBcomboBox.DropDownStyle = ComboBoxStyle.DropDownList;

                

                Cursor.Current = Cursors.Default;

                
                this.Hide();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Please enter correct username/password,"+ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
        }

        private void rdbtnLogin_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbtnLogin.Checked == true)
            {

                txtBoxServerName.Text = "";
                txtBoxUserName.Text = "";
                txtBoxPwd.Text = "";

                txtBoxServerName.ReadOnly = true;
                txtBoxUserName.ReadOnly = true;
                txtBoxPwd.ReadOnly = true;

                errorProvider1.Clear();
                button1.Enabled = true;
                
            }

            if (rdbtnSQLLogin.Checked == true)
            {
                
                txtBoxServerName.ReadOnly = false;
                txtBoxUserName.ReadOnly = false;
                txtBoxPwd.ReadOnly = false;

                txtBoxServerName.Tag = "Please enter a Server name";
                txtBoxUserName.Tag = "Please enter a User name";
                txtBoxPwd.Tag = "Please enter a Password";
                errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;

                ValidateTextBox(txtBoxServerName, EventArgs.Empty);
                ValidateTextBox(txtBoxUserName, EventArgs.Empty);
                ValidateTextBox(txtBoxPwd, EventArgs.Empty);

            }
        }

        private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((txtBoxServerName.SelectionStart == 0) && (e.KeyChar == (char)Keys.Space) || (txtBoxUserName.SelectionStart == 0) && (e.KeyChar == (char)Keys.Space) || (txtBoxPwd.SelectionStart == 0) && (e.KeyChar == (char)Keys.Space))
            {
                e.Handled = true;
            }
        }

        private void txtBoxServerName_TextChanged(object sender, EventArgs e)
        {
            //Store the back up of Current Cursor Possition.
            int cusorpos = txtBoxServerName.SelectionStart;

            if (false == string.IsNullOrEmpty(txtBoxServerName.Text))
            {
                if (txtBoxServerName.Text[0] == ' ')
                {
                    //Trim Spaces at beginning.
                    txtBoxServerName.Text = txtBoxServerName.Text.TrimStart(' ');

                    //Set the Cursor position to current Position. 
                    txtBoxServerName.SelectionStart = cusorpos;
                }
            }
        }

        private void txtBoxUserName_TextChanged(object sender, EventArgs e)
        {
            int cusorpos = txtBoxUserName.SelectionStart;

            if (false == string.IsNullOrEmpty(txtBoxUserName.Text))
            {
                if (txtBoxUserName.Text[0] == ' ')
                {
                    //Trim Spaces at beginning.
                    txtBoxUserName.Text = txtBoxUserName.Text.TrimStart(' ');

                    //Set the Cursor position to current Position. 
                    txtBoxUserName.SelectionStart = cusorpos;
                }
            }
        }

        //private void txtBoxUserName_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if ((txtBoxUserName.SelectionStart == 0) && (e.KeyChar == (char)Keys.Space))
        //    {
        //        e.Handled = true;
        //    }
        //}

        private void txtBoxPwd_TextChanged(object sender, EventArgs e)
        {
            int cusorpos = txtBoxPwd.SelectionStart;

            if (false == string.IsNullOrEmpty(txtBoxPwd.Text))
            {
                if (txtBoxPwd.Text[0] == ' ')
                {
                    //Trim Spaces at beginning.
                    txtBoxPwd.Text = txtBoxPwd.Text.TrimStart(' ');

                    //Set the Cursor position to current Position. 
                    txtBoxPwd.SelectionStart = cusorpos;
                }
            }

        }

        //private void txtBoxPwd_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    if ((txtBoxPwd.SelectionStart == 0) && (e.KeyChar == (char)Keys.Space))
        //    {
        //        e.Handled = true;
        //    }

        //}


        private HashSet<Control> errorControls = new HashSet<Control>();

        private void ValidateTextBox(object sender, EventArgs e)
        {
            txtBoxServerName_TextChanged(null,null);
            txtBoxUserName_TextChanged(null, null);
            txtBoxPwd_TextChanged(null, null);  

            var textBox = sender as TextBox;
            if (textBox.Text == "")
            {
                errorProvider1.SetError(textBox, (string)textBox.Tag);
                errorControls.Add(textBox);
            }
            else
            {
                errorProvider1.SetError(textBox, null);
                errorControls.Remove(textBox);
            }
            button1.Enabled = errorControls.Count == 0;
        }

      

    }
}
